from PIL import Image, ImageFont, ImageDraw
from datetime import date
from chapterlib import chapter_generator
import re

# 默认的模板
template_text = '''☀心满意足餐厅☀

{date}

♥每日灵奶:
▶{dujing1}
▶{dujing2}

✿每日配菜:
▶{daogao}
▶选取当日读的章节中有感动的经文祷告

★自由选择两项搭配★

★营养丰富，请勿错过★'''

class DailyDujingDaogaoImg:

    def __init__(self, dujing_1: str = '创1-2', dujing_2: str = '太1', daogao_info=['为自己的心祷告', '为我们的父母祝福祷告'], share_date=date.today()):

        self.__bg_img__ = 'bg_img/default_bg.jpg'
        self.__template__ = template_text
        self.dujing_1 = dujing_1
        self.dujing_2 = dujing_2
        self.daogao_info = daogao_info
        self.share_date = share_date

    @property
    def bg_img(self):
        return self.__bg_img__

    @bg_img.setter
    def bg_img(self, _bg_img_):
        self.__bg_img__ = _bg_img_

    @property
    def template(self):
        return self.__template__

    @template.setter
    def template(self, text):
        self.__template__ = text

    def get_text(self):
        template = self.template

        newlines = []
        daogao_text = ''
        pattern = r'(.*){daogao}(.*)'

        if m := re.search(pattern, template, re.MULTILINE):
            prefix = m.group(1)
            suffix = m.group(2)
            template = re.sub(pattern, '{daogao}', template)

            for line in self.daogao_info:
                newlines.append(prefix + line.strip() + suffix)
                
            daogao_text = '\n'.join(newlines)

        text_raw = template.format(date=self.get_date_info(), dujing1=self.dujing_1, dujing2=self.dujing_2, daogao=daogao_text)
        
        # 以下代码可以用Python3.12的itertools.batch函数完成
        # 实践证明, itertools.batch还不如以下的实现
        row_len = 17
        text_lines = []
        for line in text_raw.splitlines():
            line = line.rstrip()
            if (char_sum := len(line)) > row_len:
                batches = []
                for batch_start in range(0, char_sum, row_len+1):
                    batch_end = batch_start + row_len+1
                    if batch_end > char_sum:
                        batch_end = char_sum
                    batches.append(line[batch_start:batch_end])
                line = '\n'.join(batches)
            text_lines.append(line)
        return '\n'.join(text_lines)


    def get_week_info(self):
        week_dict = {1: '周一', 2: '周二', 3: '周三',
                     4: '周四', 5: '周五', 6: '周六', 7: '周日'}
        return week_dict.get(self.share_date.isoweekday())

    def get_date_info(self):
        return f'{self.share_date.month:02}月{self.share_date.day:02}日 {self.get_week_info()}'

    def generate_img(self, img_uri=None):

        img = Image.open(self.bg_img)

        # thumbnail方法会保持原图长宽比例, 这里不适用
        # img.thumbnail((720,9999))
        # 添加抗锯齿resample=Image.LANCZOS
        
        # 720:1920约分9:16
        #img_w = 720
        img_w = 1080

        #img_h = 1152
        img_h = 1920

        w, h = img.size
        if not w == img_w or not h == img_h:
            img = img.resize((img_w, img_h))

        # 字体
        #font = ImageFont.truetype('fonts/NotoSansHans-Regular.ttf', 35)
        font = ImageFont.truetype('fonts/NotoSansHans-Regular.ttf', 56)

        # 行间距
        space = 35
        draw = ImageDraw.Draw(img)

        text = self.get_text()

        __, __, text_w, text_h = draw.multiline_textbbox(
            (0, 0), text, font, spacing=space, stroke_width=1, embedded_color=True)
        if text_h > img_h:
            img_h = text_h+128
            img = img.resize((img_w, img_h))
            draw = ImageDraw.Draw(img)
        xy = (img_w-text_w)/2, (img_h-text_h)/2
        draw.multiline_text(xy, text, (255, 255, 255), font, spacing=space,
                            stroke_width=1, stroke_fill=(0, 0, 0), embedded_color=True)

        if img_uri in ('__temp_default__', '__temp__'):
            img.save('__justforshow__.jpg','jpeg')
            img = img.resize((324, 576))

        img.save(img_uri, 'jpeg')
        img.close()
